import 'package:dio/dio.dart';
import 'package:get/get.dart';
import 'package:hygf/config/ApiConfig.dart';
import 'package:hygf/page/home/customer_profile/state.dart';

import '../../../../util/HDNavigator.dart';
import '../../../bean/CustomerList.dart';
import '../../../http/DioClient.dart';
import '../../../http/core/ResponseData.dart';
import '../../../util/LoadingUtils.dart';

class CustomerProfileLogic extends GetxController {
  final CustomerProfileState state = CustomerProfileState();

  @override
  void onReady() {
    super.onReady();
    LoadingUtils.loading();
    requestList(true);
  }

  /// 列表刷新，isRefresh：true是刷新，false加载更多
  void requestList(bool isRefresh, {String? selectedType,String? searchKey}) async {
    /// 如果是刷新，初始化参数
    if (isRefresh) {
      state.pageNum = 1;
      state.noMore = false;
      state.controller.resetLoadState();
    }

    Map<String, dynamic> data = {
      "pageNum": state.pageNum,
      "pageSize": state.pageSize
    };
    if(searchKey != null){
        data["nameOrNumber"] = searchKey;
    }
    if(selectedType != null){
      if(selectedType != "全部"){
        int status = 0;
        switch (selectedType){
          case "待踏勘":
            status = 3;
            break;
          case "踏勘待审核":
            status = 5;
            break;
          case "待设计":
            status = 7;
            break;
          case "待报审":
            status = 11;
            break;
          case "待施工":
            status = 15;
            break;
          case "待并网":
            status = 19;
            break;
          case "待验收":
            status = 23;
            break;
        }
        data["status"] = status;
      }
    }
    ResponseData responseData = await DioClient().doPost(ApiConfig.customerPage,
        data: data, options: Options(extra: {"hideLoading": true}));
    LoadingUtils.dismiss();
    if (responseData.isok) {
      dynamic result = Customerlist.fromJson(responseData.data);
      if (isRefresh) {
        state.dataList.clear();
        state.controller.finishRefresh();
      }
      state.dataList.addAll(result.list ?? []);
      state.noMore = !(state.pageNum * state.pageSize < (result.total ?? 0));
      state.pageNum++;
      state.controller.finishLoad(noMore: state.noMore);
      update();
    } else {
      state.controller.finishRefresh();
      state.noMore = true;
      update();
    }
  }

  closePage() {
      HDNavigator.close();
  }

  @override
  void onClose() {
    state.controller.dispose();
    super.onClose();
  }
}
